package safety;

import java.util.ArrayList;
import java.util.List;

/**
 * 安全控制器
 * 使用责任链模式处理安全事件
 */
public class SafetyController {
    private List<SafetyHandler> handlers = new ArrayList<>();
    private SafetyHandler chainHead;

    public void registerHandler(SafetyHandler handler) {
        handlers.add(handler);
        buildChain();
    }

    public void unregisterHandler(SafetyHandler handler) {
        handlers.remove(handler);
        buildChain();
    }

    private void buildChain() {
        if (handlers.isEmpty()) {
            chainHead = null;
            return;
        }

        // 按优先级排序处理器
        handlers.sort((h1, h2) -> Integer.compare(h2.getPriority(), h1.getPriority()));

        // 构建责任链
        chainHead = handlers.get(0);
        SafetyHandler current = chainHead;

        for (int i = 1; i < handlers.size(); i++) {
            current.setNextHandler(handlers.get(i));
            current = handlers.get(i);
        }

        // 最后一个处理器的下一个为null
        current.setNextHandler(null);
    }

    public void handleSafetyEvent(SafetyEvent event) {
        System.out.println("收到安全事件: " + event);

        if (chainHead != null) {
            chainHead.handleEvent(event);
        } else {
            System.out.println("警告: 没有注册任何安全处理器，事件无法处理");
        }
    }
}